<?php

namespace app\commission;

use app\models\City;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;

/**
 * 返佣
 *
 * Class ReturnCommission
 * @package app\commission
 */
class ReturnCommission
{
    protected $user;
    protected $order;
    protected $set;

    public function __construct(\app\models\order\Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        // 报单区才有佣金
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {

            // 商品佣金
            $this->productCommission();

            // 首购 与 复购
            // if ($this->user->repeat == 0) {
            if (!Product::checkRepeat($this->user, $this->order->id)) {
                $this->report();

                // 记录首购
                $this->user->repeat = 1;
                $this->user->save();
            } else {
                $this->repeat();
            }
        }
    }

    // 处理出局 ( 前2个, 是没有间推奖的 )
    // protected function get2($user_id)
    // {
    //     // 需要找链上的合伙人(跳过区代)
    //     $vip2_one = Chain::getReferrerChainOne($user_id, [UserLevel::$keys['vip2']], true);
    //
    //     // 如果此人已经有2个直推 "代理", 则继续找上级
    //     if ($vip2_one) {
    //         $children = Chain::getChildrenLevel($vip2_one->id, [UserLevel::$keys['vip1'], UserLevel::$keys['vip2'], UserLevel::$keys['svip1'], UserLevel::$keys['svip2']]);
    //
    //         if ($children && count($children) > 2) {
    //             return $this->get2($vip2_one->id);
    //         } else {
    //             return $vip2_one;
    //         }
    //     }
    //
    //     return null;
    // }

    // todo 可能这个更正确
    public function getRealFinal($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 如果推荐人是股东
        if ($the_referrer->level == UserLevel::$keys['vip2']) {
            // 判断是否属于前2单
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getRealFinal($the_referrer->id);
                }
            } else {
                return $this->getRealFinal($the_referrer->id);
            }
        }

        return $this->getRealFinal($the_referrer->id);

    }

    // 获取真正拿间推奖的人(出局处理)
    protected function getReal($referrer_id)
    {
        // a -> b -> c 购买, 找 a
        // 找到订单推荐人的上级, 如果是 代理, 则找链上的合伙人
        // 否则, 判断推荐人是不是 合伙人的 前两个直推
        // 是, 继续找链上的合伙人
        // 否则, 就应该是此人(第3个推荐了)

        $the_referrer = Chain::getReferrer($referrer_id, true);
        if (!$the_referrer) {
            return null;
        }

        if ($the_referrer->level == UserLevel::$keys['vip2']) {
            // 如果是合伙人, 判断推荐是不是前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
            }
            // var_dump($children);exit;
            $in = in_array($referrer_id, $children);
            if ($in) {
                return Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
            } else {
                return $the_referrer;
            }

        // } else if ($the_referrer->level == UserLevel::$keys['vip1']) {
        } else {
            // 如果是代理, (区代,市代) , 则直接找链上的合伙人
            return Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
        }
    }

    // 首购奖
    protected function report()
    {
        $referrer = Chain::getReferrer($this->user->id, true);

        if ($referrer) {

            // 代理
            if ($referrer->level == UserLevel::$keys['vip1']) {

                // 直推奖
                $balance = $this->set['vip1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 11, '销售提成');

                $the_referrer = $this->getReal($referrer->id);
                if ($the_referrer) {

                    // 间推奖
                    $balance = $this->set['vip2_2'];
                    $this->saveCommission($the_referrer['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');

                    // 平级奖
                    $with_referrer =  Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
                    // var_dump($the_referrer, $with_referrer);exit;
                    if ($with_referrer) {
                        $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                        $this->saveCommission($with_referrer['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                    }
                }

                // 需要找链上的合伙人(跳过区代)
                // $vip2_list = Chain::getReferrerChain($referrer->id, [UserLevel::$keys['vip2']], true);
                // if ($vip2_list) {
                //     // 间推奖
                //     $balance = $this->set['vip2_2'];
                //     $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');
                //
                //     if (count($vip2_list) >= 2) {
                //         // 平级奖
                //         // $balance = $this->set['vip2_2'];
                //         $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                //         $this->saveCommission($vip2_list[1]['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                //     }
                // }

                // $vip2_one = $this->get2($referrer->id);
                // // var_dump($vip2_one);exit;
                // if ($vip2_one) {
                //     // 间推奖
                //     $balance = $this->set['vip2_2'];
                //     $this->saveCommission($vip2_one['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');
                //
                //     // 平级奖
                //     $equal_one = Chain::getReferrerChainOne($vip2_one->id, [UserLevel::$keys['vip2']], true);
                //     if ($equal_one) {
                //         $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                //         $this->saveCommission($equal_one['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                //     }
                // }
            }

            // 合伙人
            if ($referrer->level == UserLevel::$keys['vip2']) {
                // 直推奖
                $balance = $this->set['vip2_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 21, '销售提成');

                // 需要找链上的合伙人(跳过区代)
                $vip2_list = Chain::getReferrerChain($referrer->id, [UserLevel::$keys['vip2']], true);
                if ($vip2_list) {
                    // 这里没有间推奖了, 只有平级奖
                    // $balance = $this->set['vip2_2'];
                    $balance = $this->set['vip2_1'] * $this->set['vip2_3'] / 100;
                    $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 23, '销售提成');

                    // // 间推奖
                    // $balance = $this->set['vip2_2'];
                    // $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 22, '销售提成');
                    //
                    // if (count($vip2_list) >= 2) {
                    //     // 平级奖
                    //     // $balance = $this->set['vip2_2'];
                    //     $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                    //     $this->saveCommission($vip2_list[1]['id'], $this->order->user_id, $this->order->id, $balance, 23, '培训补助');
                    // }
                }
            }

            // 区代
            if ($referrer->level == UserLevel::$keys['svip1']) {
                // 直推奖
                $balance = $this->set['svip1_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 31, '销售提成');
            }

            // 市代
            if ($referrer->level == UserLevel::$keys['svip2']) {
                // 直推奖
                $balance = $this->set['svip2_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 41, '销售提成');
            }
        }

        // 区域奖
        $area = $this->getAreaUser();
        if ($area[0]) {
            $balance = $this->set['svip1_2'];
            $this->saveCommission($area[0]['id'], $this->order->user_id, $this->order->id, $balance, 98, '区域奖');
        }
        if ($area[1]) {
            $balance = $this->set['svip2_2'];
            $this->saveCommission($area[1]['id'], $this->order->user_id, $this->order->id, $balance, 98, '区域奖');
        }
    }

    // 获取域区
    protected function getAreaUser()
    {
        $area_id = UserAddress::find()
            ->where(['id' => $this->order->user_address])
            ->select(['table_id'])
            ->scalar();
        $city_id = City::find()
            ->where(['area_id' => $area_id])
            ->select(['city_id'])
            ->scalar();

        $svip1 = User::find()
            ->where(['level' => UserLevel::$keys['svip1']])
            ->andWhere(['address_up' => $area_id])
            ->orderBy(['update_time' => SORT_DESC])
            ->one();
        $svip2 = User::find()
            ->where(['level' => UserLevel::$keys['svip2']])
            ->andWhere(['address_up' => $city_id])
            ->orderBy(['update_time' => SORT_DESC])
            ->one();

        // var_dump($area_id, $city_id);exit;

        return [$svip1, $svip2];
    }

    // 复购奖
    protected function repeat()
    {
        // 差价奖(上级 也是 repeat = 1 )
        // 用这种方式, 购物车也是正确的
        $vip1_price = $this->set['diff_vip1'];
        $vip2_price = $this->set['diff_vip2'];
        $svip1_price = $this->set['diff_svip1'];
        $svip2_price = $this->set['diff_svip2'];

        $current_price = $vip1_price;
        if ($this->user->level === UserLevel::$keys['vip2']) {
            $current_price = $vip2_price;
        }
        if ($this->user->level === UserLevel::$keys['svip1']) {
            $current_price = $svip1_price;
        }
        if ($this->user->level === UserLevel::$keys['svip2']) {
            $current_price = $svip2_price;
        }

        $diff_vip2 = 0;
        $diff_svip1 = 0;
        $diff_svip2 = 0;

        // 如果关系链是乱调的, 需要用foreach ....
        $chain = Chain::getReferrerChain($this->user->id,
            [UserLevel::$keys['vip2'], UserLevel::$keys['svip1'], UserLevel::$keys['svip2']],
            true);
        foreach ($chain as $u) {
            if ($u->level <= $this->user->level) {
                continue;
            }
            if (!$diff_svip2 && !$diff_svip1 && !$diff_vip2 && $u->level == UserLevel::$keys['vip2']) {
                $temp = $current_price - $vip2_price;
                if ($temp > 0) {
                    $diff_vip2 = $temp;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_vip2, 88, '复购差价');
                }
            }
            if (!$diff_svip2 && !$diff_svip1 && $u->level == UserLevel::$keys['svip1']) {
                $temp = $current_price - $svip1_price;
                if ($temp > 0) {
                    $diff_svip1 = $temp - $diff_vip2;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_svip1, 88, '复购差价');
                }
            }
            if (!$diff_svip2 && $u->level == UserLevel::$keys['svip2']) {
                $temp = $current_price - $svip2_price;
                if ($temp > 0) {
                    $diff_svip2 = $temp - $diff_svip1 - $diff_vip2;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_svip2, 88, '复购差价');
                    break;
                }
            }
        }

        // $vip2 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['vip2']]);
        // $svip1 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['svip1']]);
        // $svip2 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['svip2']]);
        //
        // if ($vip2 && $vip2->level > $this->user->level) {
        //     $temp = $current_price - $vip2_price;
        //     if ($temp > 0) {
        //         $diff_vip2 = $temp;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_vip2, 88, '复购差价');
        //     }
        // }
        // if ($svip1 && $svip1->level > $this->user->level) {
        //     $temp = $current_price - $svip1_price;
        //     if ($temp > 0) {
        //         $diff_svip1 = $temp - $diff_vip2;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_svip1, 88, '复购差价');
        //     }
        // }
        // if ($svip2 && $svip2->level > $this->user->level) {
        //     $temp = $current_price - $svip2_price;
        //     if ($temp > 0) {
        //         $diff_svip2 = $temp - $diff_svip1 - $diff_vip2;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_svip2, 88, '复购差价');
        //     }
        // }

        // 区域奖
        $area = $this->getAreaUser();
        if ($area[0]) {
            $balance = $this->set['svip1_3'];
            $this->saveCommission($area[0]['id'], $this->order->user_id, $this->order->id, $balance, 99, '区域奖');
        }
        if ($area[1]) {
            $balance = $this->set['svip2_3'];
            $this->saveCommission($area[1]['id'], $this->order->user_id, $this->order->id, $balance, 99, '区域奖');
        }
    }

    // 总商品佣金列表
    protected function productCommission()
    {
        $list = [];
        $items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->with(['product.commissionDiff'])
            ->asArray()
            ->all();

        foreach ($items as &$item) {
            $commission = $item['product']['commissionDiff'];
            foreach ($commission as $key => &$c) {
                // 直推合伙人所有收益的 10%
                if ($key == 'vip2_3') {
                    // $c = $c * $commission['vip2_1'] / 100 / $item['quantity'];
                    continue;
                }

                // 数量
                $c = $c * $item['quantity'];
            }
            array_push($list, $commission);
        }

        /*
         * 每二维数组合成1维数组
         * array(1) {
          [0]=>
          array(16) {
            ["id"]=>
            int(11)
            ["product_id"]=>
            int(1008)
            ["vip1"]=>
            float(5000)
            ["vip2_1"]=>
            float(7000)
            ["vip2_2"]=>
            float(2000)
            ["vip2_3"]=>
            float(700)
            ["svip1_1"]=>
            float(7000)
            ["svip1_2"]=>
            float(300)
            ["svip1_3"]=>
            float(10)
            ["svip2_1"]=>
            float(7000)
            ["svip2_2"]=>
            float(1000)
            ["svip2_3"]=>
            float(15)
            ["diff_vip1"]=>
            float(400)
            ["diff_vip2"]=>
            float(340)
            ["diff_svip1"]=>
            float(300)
            ["diff_svip2"]=>
            &float(240)
          }
        }
         */
        $temp = [];
        foreach ($list as $value) {
            foreach ($value as $k => $v) {

                if ($k == 'product_id' || $k == 'id') {
                    continue;
                }

                if (key_exists($k, $temp)) {
                    $temp[$k] += $v;
                } else {
                    $temp[$k] = $v;
                }
            }
        }

        // var_dump($list, $temp);exit;
        $this->set = $temp;

    }

    // 保存佣金
    protected function saveCommission($user_id, $fans_id, $order_id, $balance, $type, $name)
    {
        if ($balance > 0) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $balance;
                $account->save();
            }
        }
    }

}